package com.java.basis.thread.n3.exercise;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author wangning
 * @create 2022-01-19 10:41
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {
	public static void main(String[] args) throws InterruptedException {
		//模拟多人买票
		TicketWindow window = new TicketWindow(1000);

		//所有线程的集合
		List<Thread> threadList = new ArrayList<>();
		//统计卖出的票数统计
		List<Integer> amountList = new Vector<>();
		/**
		 * 为什么卖出的票数统计不可以使用 List<Integer> sellCount = new ArrayList<>();？？？
		 *
		 */
		for (int i = 0; i < 2000; i++) {
			Thread thread = new Thread(() -> {
				int amount = window.sell(randomAmount());
//				try {
//					Thread.sleep(randomAmount()*10L);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
				amountList.add(amount);
			});
			threadList.add(thread);
			thread.start();

		}
		for (Thread thread : threadList) {
			thread.join();
		}
		//统计卖出的票数和剩余的票数
		log.debug("余票：{}", window.getCount());
		log.debug("卖出票数：{}", amountList.stream().mapToInt(i -> i).sum());

	}

	//Random 为线程安全
	static Random random = new Random();

	//随机1-5
	public static int randomAmount() {
		return random.nextInt(5) + 1;
	}

}

@Slf4j(topic = "c.TicketWindow")
class TicketWindow {
	private int count;

	public TicketWindow(int count) {
		this.count = count;
	}

	public int getCount() {
		return count;
	}

	public synchronized  int sell(int amount) {
		if (this.count >= amount) {
			this.count -= amount;
			return amount;
		} else {
			return 0;
		}
	}
}
